import 'package:flutter/material.dart';
import 'package:my_demo_flutter/my_base_lib/base_lib.dart';

class RefreshAndLoadMorePage extends StatefulWidget {
  static String routeName = "/RefreshAndLoadMorePage";

  const RefreshAndLoadMorePage({Key? key}) : super(key: key);

  @override
  _RefreshAndLoadMorePageState createState() => _RefreshAndLoadMorePageState();
}

class _RefreshAndLoadMorePageState extends State<RefreshAndLoadMorePage> {
  late String timeStr;
  List<String> datas = [];
  ScrollController _scrollController =ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        // 当滚动到底部时，加载更多数据
        _loadMore();
      }

    });

    timeStr = DateTime.now().toString();
    for (int i = 0; i < 30; i++) {
      datas.add("item-$i 时间:$timeStr");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: () async {
          LogUtils.e("开始刷新");
          await Future.delayed(Duration(seconds: 2));
          LogUtils.e("结束刷新");
          setState(() {
            timeStr = DateTime.now().toString();
            datas.clear();
            for (int i = 0; i < 30; i++) {
              datas.add("item-$i 时间:$timeStr");
            }
          });
        },
        child: ListView.builder(
          controller: _scrollController,
          itemCount: datas.length,
          itemBuilder: (context, index) {
            return SizedBox(
              height: 60,
              child: Text(datas[index]),
            );
          },
        ),
      ),
    );
  }

  bool loadingMore = false;
  void _loadMore() async{
    if(!loadingMore){
      loadingMore = true;
      await Future.delayed(const Duration(seconds: 2));
      setState(() {
        for(int i = 0;i<10;i++){
          datas.add("item-${datas.length} 时间:$timeStr");
        }
      });
    }
    loadingMore = false;
  }
}
